/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package admin.Controller;

import Exception.KwickKioskDBException;
import admin.BusinessLogic.BusinessLogic;
import admin.BusinessLogic.LineChart;
import admin.BusinessLogic.Validation;
import admin_gui.Admin_ChartReport;
import admin_gui.Admin_GenerateReportStore;
import admin_gui.Admin_SelectStoreReport;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;

/**
 *
 * @author WEN
 */
public class StoreReportController {

    private BusinessLogic businesslogic;
    private JPanel mainPanel;
    private Vector store;
    private boolean [] storeItem;
    private double quantity,sales,profit;
    private Validation validation;
    public StoreReportController(JPanel MainPanel) {
        validation = new Validation();
        quantity = 0;
        sales = 0;
        profit = 0;
        try {
            businesslogic = new BusinessLogic();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(StoreReportController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(StoreReportController.class.getName()).log(Level.SEVERE, null, ex);
        }
        mainPanel = MainPanel;
        store = new Vector();
        storeItem = new boolean[4];
        storeItem[0] = true;
        for (int i = 1; i < 4; i++) {
            storeItem[i] = false;
        }
    }

    public StoreReportController() {
        validation = new Validation();
        try {
            businesslogic = new BusinessLogic();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(StoreReportController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(StoreReportController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void manageStore(JTable ResultTable, Vector v_head,
            String searchField, boolean[] storeItem) {
        this.storeItem = storeItem;
        if (storeItem[0] == true) {
            showStoreTable(ResultTable, v_head);
        } else if (storeItem[1]) {
            showStoreTableByName(searchField.trim(), ResultTable, v_head);
        } else if (storeItem[2]) {
            showStoreTableByPosCode(searchField.trim(), ResultTable, v_head);
        } else if (storeItem[3]) {
            showStoreTableByCity(searchField.trim(), ResultTable, v_head);
        } else if (storeItem[4]) {
            showStoreTableByProvince(searchField.trim(), ResultTable, v_head);
        } else {
            JOptionPane.showMessageDialog(null,
                    "Sorry! Can not find that information",
                    "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void showStoreTable(JTable ResultTable, Vector v_head) {
        store = businesslogic.getStoresReport();
        DefaultTableModel tm = new DefaultTableModel(store, v_head);
        ResultTable.setModel(tm);
        ((DefaultTableModel) ResultTable.getModel()).fireTableStructureChanged();
    }

    private void showStoreTableByName(String name, JTable ResultTable,
            Vector v_head) {
        store.clear();
        store = businesslogic.getStoresReportByStoreName(name);
        DefaultTableModel tm = new DefaultTableModel(store, v_head);
        ResultTable.setModel(tm);
        ((DefaultTableModel) ResultTable.getModel()).fireTableStructureChanged();
    }

    private void showStoreTableByPosCode(String posCode, JTable ResultTable,
            Vector v_head) {
        store.clear();
        store = businesslogic.getStoresReportByStorePosCode(posCode);
        DefaultTableModel tm = new DefaultTableModel(store, v_head);
        ResultTable.setModel(tm);
        ((DefaultTableModel) ResultTable.getModel()).fireTableStructureChanged();
    }

    private void showStoreTableByCity(String city, JTable ResultTable,
            Vector v_head) {
        store.clear();
        store = businesslogic.getStoresReportByStoreCity(city);
        DefaultTableModel tm = new DefaultTableModel(store, v_head);
        ResultTable.setModel(tm);
        ((DefaultTableModel) ResultTable.getModel()).fireTableStructureChanged();
    }

    private void showStoreTableByProvince(String province, JTable ResultTable,
            Vector v_head) {
        store.clear();
        store = businesslogic.getStoresReportByStoreProvince(province);
        DefaultTableModel tm = new DefaultTableModel(store, v_head);
        ResultTable.setModel(tm);
        ((DefaultTableModel) ResultTable.getModel()).fireTableStructureChanged();
    }

    public void showStoreReport(ArrayList rlist) {
        Admin_GenerateReportStore storeReport = new Admin_GenerateReportStore(
                rlist, mainPanel);
        storeReport.setBounds(1, 1, 762, 613);
        mainPanel.removeAll();
        mainPanel.add(storeReport);
        mainPanel.validate();
        mainPanel.repaint();
    }

    public void showStoreReportTable(JTable ResultTable,
            ArrayList<String> reporList,
            String startDate, String endDate, Vector<String> v_head) {
        quantity = 0;
        sales = 0;
        profit = 0;
        Vector report_vec = new Vector();
        report_vec = businesslogic.storeReport(reporList, startDate, endDate);
        for (int j = 0; j < report_vec.size(); j++) {
            quantity = quantity + Double.parseDouble((String) ((Vector) report_vec.get(
                    j)).get(1));
            sales = sales + Double.parseDouble((String) ((Vector) report_vec.get(
                    j)).get(2));
            profit = profit + Double.parseDouble((String) ((Vector) report_vec.get(
                    j)).get(3));
        }
        DefaultTableModel tm = new DefaultTableModel(report_vec, v_head);
        ResultTable.setModel(tm);
        ((DefaultTableModel) ResultTable.getModel()).fireTableStructureChanged();
    }

    public void generateReportChart(ArrayList<String> reportList,
            String startDate, String endDate, boolean flag) {
        Vector report_vec = new Vector();
        JPanel chartPanel = new JPanel();
        report_vec = businesslogic.storeReport(reportList, startDate, endDate);
        String[] report_str = new String[report_vec.size()];
        for (int j = 0; j < report_vec.size(); j++) {
            report_str[j] = (String) ((Vector) report_vec.get(j)).get(0);
        }
        Admin_ChartReport chartReport = new Admin_ChartReport(mainPanel,
                reportList, 2, startDate, endDate);
        if (flag) {
            chartPanel = getLineChart(report_str, startDate, endDate);
        } else {
            chartPanel = getPieChart(report_vec);
        }

        chartPanel.setBounds(1, 1, 750, 500);
        chartReport.add(chartPanel);
        chartReport.validate();
        chartReport.repaint();
        chartReport.setBounds(1, 1, 762, 613);
        mainPanel.removeAll();
        mainPanel.add(chartReport);
        mainPanel.validate();
        mainPanel.repaint();
    }

    private JPanel getLineChart(String[] report_str, String startDate,
            String endDate) {
        JPanel temp = new JPanel();
        LineChart lineChart = new LineChart();
        String splitStartDate [] = new String [3];
        String splitEndDate [] = new String [3];
        int flag = validation.validReportDate(startDate, endDate);
        try {
            if(flag == 1){
                splitStartDate = startDate.split("-");
                splitEndDate = endDate.split("-");
                startDate = splitStartDate[0]+"-01-01";
                endDate = splitEndDate[0]+"-12-31";
                temp = lineChart.createStoreYearPanel(report_str, startDate, endDate);
            }else if(flag == 2 ){
                splitStartDate = startDate.split("-");
                startDate = splitStartDate[0]+"-"+splitStartDate[1]+"-"+"01";
                endDate = validation.getMonthReport(endDate);
                temp = lineChart.createStoreMthPanel(report_str, startDate, endDate);
            }else if(flag == 3){
                temp = lineChart.createStorePanel(report_str, startDate, endDate);
            }else{
                JOptionPane.showMessageDialog(null, "Sorry! Invalid date",
                    "Error", JOptionPane.ERROR_MESSAGE);
            }
        } catch (KwickKioskDBException ex) {
            JOptionPane.showMessageDialog(null, "Sorry! Can not connect to the server",
                    "Error", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(ItemReportController.class.getName()).log(Level.SEVERE, null, ex);
        }
        return temp;
    }

    public JPanel getPieChart(Vector report_vect) {
        DefaultPieDataset data = new DefaultPieDataset();
        for (int i = 0; i != report_vect.size(); i++) {
            data.setValue((Comparable) ((Vector) report_vect.get(i)).get(0),
                    Double.parseDouble((String) ((Vector) report_vect.get(i)).get(
                    3)));
        }
        // create a chart...
        JFreeChart chart = ChartFactory.createPieChart(
                "Profit Pie Chart",
                data,
                true, // legend?
                true, // tooltips?
                false // URLs?
                );
        // create and display a frame...
        ChartPanel panel = new ChartPanel(chart);
        return panel;
    }

    public ArrayList<Double> getTotalInfo() {
        ArrayList<Double> totalInfo = new ArrayList<Double>();
        totalInfo.add(quantity);
        totalInfo.add(sales);
        totalInfo.add(profit);
        return totalInfo;
    }

    public void goBackSelectReport() {
        Admin_SelectStoreReport selectAreaPane = new Admin_SelectStoreReport(
                mainPanel);
        selectAreaPane.setBounds(1, 1, 762, 613);
        mainPanel.removeAll();
        mainPanel.add(selectAreaPane);
        mainPanel.validate();
        mainPanel.repaint();
    }

    public void goBackStoreReportPan(JPanel mainJPanel,
            ArrayList<String> reportList, String startDate, String endDate) {
        Admin_GenerateReportStore storeReport = new Admin_GenerateReportStore(
                reportList, mainJPanel, startDate, endDate);
        storeReport.setBounds(1, 1, 762, 613);
        mainJPanel.removeAll();
        mainJPanel.add(storeReport);
        mainJPanel.validate();
        mainJPanel.repaint();
    }
}
